<template>
  <div class="my-container">
    <el-scrollbar>
      <!-- 菜单项 -->
      <el-menu
        ref="menuRef"
        :default-active="activeTab"
        class="el-menu-vertical-demo"
        :collapse="isCollapse"
        active-text-color="#409eff"
        background-color="#141c36"
        text-color="#fff"
        unique-opened
      >
        <template v-for="menuItem in menuList" :key="menuItem.name">
          <!-- 一级菜单 -->
          <el-sub-menu
            v-if="menuItem.children && menuItem.children.length > 0"
            :index="menuItem.name"
          >
            <template #title>
              <el-icon><component :is="menuItem.icon"></component></el-icon>
              <span>{{ menuItem.label }}</span>
            </template>
            <!-- 二级菜单 -->
            <template
              v-for="subMenuItem in menuItem.children"
              :key="subMenuItem.name"
            >
              <el-menu-item
                :index="subMenuItem.name"
                @click="openTab(subMenuItem)"
              >
                {{ subMenuItem.label }}
              </el-menu-item>
            </template>
          </el-sub-menu>
          <!-- 没有子菜单的一级菜单 -->
          <el-menu-item
            v-else
            :index="menuItem.name"
            @click="openTab(menuItem)"
          >
            <template #default>
              <el-icon><component :is="menuItem.icon"></component></el-icon>
              <span>{{ menuItem.label }}</span>
            </template>
          </el-menu-item>
        </template>
      </el-menu>
    </el-scrollbar>
    <el-scrollbar>
      <div ref="contentRef" class="my-content">
        <!-- Tab 页 -->
        <el-tabs
          class="my-tabs"
          v-if="activeTab"
          v-model="activeTab"
          @tab-remove="removeTab"
          @tab-click="clickTab"
        >
          <el-tab-pane
            v-for="tab in tabs"
            :key="tab.name"
            :label="tab.label"
            :name="tab.name"
          >
            <keep-alive>
              <component
                :is="tab.component"
                :data="tab"
                :key="tab.name"
              ></component>
            </keep-alive>
          </el-tab-pane>
        </el-tabs>
        <div v-else class="welcome">欢迎使用数据查询</div>
      </div>
    </el-scrollbar>
  </div>
</template>

<script lang="ts" setup>
import { markRaw, onBeforeUnmount, onMounted, reactive, ref } from "vue";
import { useRouter } from "vue-router";
import { ElMessageBox } from "element-plus";

import Component from "../template/Index.vue";
import { useMessage } from "../../hooks/useMessage";
import { Query } from "../../api/search";
import { objectToQueryParams } from "../../utils/objectToQuery";

const comObj = reactive({
  C1: markRaw(Component),
});

const message = useMessage();

//获取菜单列表
const menuList = ref<any[]>([]);
const getMenuList = async () => {
  const post = {
    groupName: "SysMgt",
    jobType: "SysInfo",
    operType: "GetMenuInfo",
  };
  const inputStr = objectToQueryParams(post);
  const res = (await Query({ inputStr })) as any;
  if (res.code !== 200) {
    message.error(res.msg);
    return;
  }
  const { menuInfo } = res.data;
  //将数据转换为所需格式
  menuInfo.map((item: any) => {
    let children: any = [];
    item.jobType.map((sub: any) => {
      children.push({
        ...sub,
        name: sub.value,
        groupName: item.value,
        jobType: sub.value,
        component: comObj[sub.template] ?? comObj['C1']
      });
    });
    menuList.value.push({
      id: item.id,
      label: item.label,
      name: item.value,
      icon: item.icon,
      children,
    });
  });
};

// 当前打开的 Tab 页数组
const tabs = ref<any[]>([]);

// 当前激活的 Tab 页
const activeTab = ref("");

// 从本地存储中恢复 Tab 状态
const restoreTabs = () => {
  const storedActiveTab = sessionStorage.getItem("WMS_ACTIVE_TAB");
  if (storedActiveTab) {
    activeTab.value = storedActiveTab;
    // 查找匹配的父元素
    const menuParent = menuList.value.filter((parent) =>
      parent.children.some((child: any) => child.name === storedActiveTab)
    );
    // 匹配对应的子元素
    const menuItem = menuParent[0].children.find(
      (item: any) => item.name === storedActiveTab
    );
    const { name, label } = menuItem;
    setBreadInfo(name, label);
    tabs.value.push(menuItem);
  }
};

// 将 Tab 状态保存到本地存储
const saveTabs = () => {
  sessionStorage.setItem("WMS_ACTIVE_TAB", activeTab.value);
};

// 打开 Tab 页
const openTab = (menuItem: any) => {
  setBreadInfo(menuItem.name, menuItem.label);

  const tabExists = tabs.value.some((tab: any) => tab.name === menuItem.name);
  if (!tabExists) {
    tabs.value.push(menuItem);
  }
  activeTab.value = menuItem.name;
  saveTabs();
  //如果menuItem包含keyType||keyValue 则表示页面跳转 组件不需要缓存
  if (menuItem.keyType) {
    setTimeout(() => {
      eventBus.emit("refreshComponent", {
        keyType: menuItem.keyType,
        keyValue: menuItem.keyValue,
      });
    }, 0);
  }
};

// 关闭 Tab 页
const removeTab = (index: string) => {
  const removedTab = tabs.value.find((tab) => tab.name === index);

  tabs.value = tabs.value.filter((tab) => tab.name !== index);
  if (activeTab.value === index) {
    activeTab.value =
      tabs.value.length > 0 ? tabs.value[tabs.value.length - 1].name : "";
    //设置面包屑数据
    if (activeTab.value) {
      setBreadInfo(
        tabs.value[tabs.value.length - 1].name,
        tabs.value[tabs.value.length - 1].label
      );
    } else {
      breadInfo.groupName = "";
      breadInfo.jobName = "";
    }
  }
  saveTabs();
};

// 选中 Tab 页
const clickTab = (tab: any) => {
  const { name, label } = tab.props;
  activeTab.value = name;
  setBreadInfo(name, label);
  saveTabs();
};

const setBreadInfo = (name: string, label: string) => {
  const tempArr = JSON.parse(JSON.stringify(menuList.value));
  // 查找匹配的父元素
  const match = tempArr.filter((parent: any) =>
    parent.children.some((child: any) => child.name === name)
  );
  breadInfo.groupName = match[0].label;
  breadInfo.jobName = label;
};

// 面包屑数据
const breadInfo = reactive({
  groupName: "",
  jobName: "",
});

import eventBus from "@/libs/eventBus";
const menuRef = ref();
const contentRef = ref();

const root = document.documentElement;
//是否折叠菜单
const isCollapse = ref(false);
const toggleCollapse = () => {
  isCollapse.value = !isCollapse.value;
  root.style.setProperty("--menu-width", isCollapse.value ? "63px" : "200px");
  //获取当前菜单和左侧内容宽度
  const menuWidth = isCollapse.value ? 63 : 200;
  const contentWidth = window.innerWidth - menuWidth;
  //通知table 宽度重新渲染
  eventBus.emit("refreshList", contentWidth);
};

const { push } = useRouter();
//退出系统
const loginOut = () => {
  ElMessageBox.confirm("是否退出本系统？", "温馨提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  })
    .then(() => {
      //调用退出接口
      localStorage.removeItem("WMS_USER");
      message.success("退出成功");
      //将Tab缓存清除
      sessionStorage.setItem("WMS_ACTIVE_TAB", "");
      activeTab.value = "";
      push({ path: "/login" });
    })
    .catch(() => {});
};

//用户登录信息
const userInfo = reactive({
  orgName: "",
  userID: "",
});

onMounted(async () => {
  root.style.setProperty("--menu-width", "200px");
  const info = localStorage.getItem("WMS_USER");
  info && Object.assign(userInfo, JSON.parse(info));
  await getMenuList();
  restoreTabs();
});

onBeforeUnmount(() => {
  eventBus.off("goToTab");
});
</script>

<style scoped lang="less">
@import url("@/style/reset.less");
.my-container {
  display: flex;
  height: calc(100vh - 56px);
}
:deep(.el-sub-menu__title){
  font-size: 16px;
}
:deep(.el-menu-item){
  font-size: 16px;
}
.el-menu-vertical-demo:not(.el-menu--collapse) {
  width: 200px;
  min-height: 400px;
}

.my-content {
  width: calc(100vw - var(--menu-width));
  padding: 10px;
  padding-top: 0;
  overflow: hidden;
}
.my-header {
  background: #2d2e42;
  height: 56px;
  color: #fff;
  :deep(.el-icon) {
    display: block;
  }
}

.btn-exit {
  color: #fff;
  font-size: 16px;
}
.welcome {
  margin: 20px auto;
  width: 430px;
  height: 430px;
  background: url("@/assets/imgs/welcome.png") no-repeat center bottom;
  background-size: contain;
  font-size: 20px;
  color: #409eff;
  letter-spacing: 5px;
  text-align: center;
  font-weight: 600;
}

.el-menu--collapse .el-sub-menu.is-active > .el-sub-menu__title i {
  // 默认折叠状态下二级菜单激活时一级菜单图标高亮
  color: var(--el-menu-active-color);
}

:deep(.el-breadcrumb__inner) {
  color: #fff !important;
}

:deep(.my-dropdown .el-dropdown-link) {
  color: #fff;
}

//定义Tab样式
:deep(.el-tabs__item){
    background: none;
    width: auto;
    padding: 5px 10px;
    font-size: 16px;
}
:deep(.el-tabs__item.is-active){
    background: none;
}
:deep(.el-tabs__active-bar){
    display: block;
}
:deep(.el-tabs__item){
  padding: 0 10px!important;
}

:deep(.el-tabs__nav-wrap:after){
  display: block;
  background-color: #143452;
}
</style>
